package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.entity.Employee;
import com.itheima.entity.Orders;
import com.itheima.entity.ShoppingCart;
import com.itheima.mapper.OrdersMapper;
import com.itheima.mapper.ShoppingCartMapper;
import com.itheima.service.IOrdersService;
import com.itheima.util.IDWorker;
import com.itheima.util.Result;
import com.itheima.util.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private IDWorker idWorker;

    @Override
    public Result submit(Orders orders) {
        //获取当前id
        Long userId = UserHolder.getUserId();
        //设置用户id
        orders.setUserId(userId);
        //设置订单号
        orders.setNumber(idWorker.nextId()+"");
        //设置订单状态
        orders.setStatus(1);
        //设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        //设置结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //设置实收金额
        //根据id获取购物车的信息
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,userId);
        ShoppingCart shoppingCart = shoppingCartMapper.selectOne(lqw);
        orders.setAmount(shoppingCart.getAmount().multiply(BigDecimal.valueOf(shoppingCart.getNumber())));
        ordersMapper.insert(orders);
        return Result.success(orders);
    }

    @Override
    public IPage<Orders> getPage(int current, int pageSize, Long number) {
        if (number != null){
            LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Orders::getId,number);
            IPage<Orders> page = new Page<Orders>(current,pageSize);
            return ordersMapper.selectPage(page,lqw);
        }
        IPage<Orders> page = new Page<Orders>(current,pageSize);
        return ordersMapper.selectPage(page,null);
    }
}
